<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/21
 * Time: 19:38
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

abstract class Cachable extends Model
{

    public static $cacheMinutes = 30;
    /**
     * @param $tag
     * @return string
     */
    protected function cacheKey($tag, $key = null)
    {
        return sprintf(
            "%s/%s",
            $this->getTable(),
            $key ?? $this->getKey()
        ) . ($tag ? "-$tag" : '');
    }

    /**
     * @param $tag
     * @return bool
     */
    public function removeCache($tag = null)
    {
        $hasForgot = Cache::forget($this->cacheKey($tag));
        logger(
            sprintf('url:%s key:%s hasforgot:%s',
            request()->url(),
            Cache::getPrefix() . $this->cacheKey($tag),
            $hasForgot ? 'yes' : 'no')
        );
        return $hasForgot;


    }

    /**
     * @return mixed
     */
    public function force()
    {
        return static::find($this->{$this->primaryKey});
    }

    /**
     * 缓存 Model
     *
     * @param $id
     * @param \Closure|null $callback
     * @return mixed
     */
    public static function findCache($id, \Closure $callback = null)
    {
        /** @var Model $class */
        $class = new static;
        return Cache::remember(
            $class->cacheKey(null, $id),
            self::$cacheMinutes,
            function () use ($id, $class, $callback) {
                $query = $class->newQuery();
                $callback && $callback($query);
                return $query->findOrFail($id);
            }
        );
    }

}